#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;

const int BUFFER_SIZE = 1024;
static const char* status_line[2] = {
    "200 OK",
    "500 Internal Server Error"
};

int main(int argc, char* argv[])
{
    if(argc <= 3)
    {
        cout << "Usage: " << argv[0] << " ip_address port_number filename" << endl;
        return 1;
    }

    const char* ip = argv[1];
    int port = atoi(argv[2]);
    const char* file_name = argv[3];

    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &address.sin_addr);
    address.sin_port = htons(port);

    int listenFd = socket(AF_INET, SOCK_STREAM, 0);
    assert(listenFd >= 0);

    int ret = bind(listenFd, (struct sockaddr*)&address, sizeof(address));
    assert(ret != -1);

    ret = listen(listenFd, 5);
    assert(ret != -1);

    struct sockaddr_in client;
    socklen_t client_addrlength = sizeof(client);
    int connFd = accept(listenFd, (struct sockaddr*)&client, &client_addrlength);
    if(connFd < 0)
    {
        cout << "errno is: " << errno << endl;
    }
    else
    {
        // HTTP应答状态行 头部字段 和空行
        char header_buf[BUFFER_SIZE];
        memset(header_buf, '\0', BUFFER_SIZE);
        // 目标文件内容的缓冲区
        char* file_buf;
        // 获取文件状态
        struct stat file_stat;
        // 记录文件是否有效
        bool vaild = true;
        // 目前头文件的缓冲区长度
        int len = 0;
        if (stat(file_name, &file_stat) < 0)
        {
            vaild = false;
        }
        else
        {
            if (S_ISDIR(file_stat.st_mode)) // 如果是目录
            {
                vaild = false;
            }
            else if (file_stat.st_mode & S_IROTH) // 如果有读权限
            {
                int fd = open(file_name, O_RDONLY);
                if (fd < 0)
                {
                    vaild = false;
                }
                else
                {
                    file_buf = new char[file_stat.st_size + 1];
                    memset(file_buf, '\0', file_stat.st_size + 1);
                    if(read(fd, file_buf, file_stat.st_size) < 0)
                    {
                        vaild = false;
                    }
                }
            }
            else
            {
                vaild = false;
            }
        }

        if(vaild)
        {
            // HTTP状态行
            ret = snprintf(header_buf, BUFFER_SIZE - 1, "%s %s\r\n", "HTTP/1.1", status_line[0]);
            len += ret;
            // HTTP头部字段
            ret = snprintf(header_buf + len, BUFFER_SIZE - len - 1, "Content-Length: %d\r\n", file_stat.st_size);
            len += ret;
            // 结束头部字段
            header_buf[len++] = '\r';
            header_buf[len++] = '\n';

            struct iovec iv[2];
            iv[0].iov_base = header_buf;
            iv[0].iov_len = len;
            iv[1].iov_base = file_buf;
            iv[1].iov_len = file_stat.st_size;
            // 使用writev发送数据
            ret = writev(connFd, iv, 2);
            if (ret < 0)
            {
                cout << "writev error: " << strerror(errno) << endl;
            }
        }
        else    // 没有目标文件
        {
            // HTTP状态行
            ret = snprintf(header_buf, BUFFER_SIZE - 1, "%s %s\r\n", "HTTP/1.1", status_line[1]);
            len += ret;
            // HTTP头部字段
            ret = snprintf(header_buf + len, BUFFER_SIZE - len - 1, "%s", "\r\n");
            send(connFd, header_buf, len + ret, 0);
        }

        close(connFd);
        if (file_buf)
        {
            delete[] file_buf; // 释放文件内容缓冲区
        }
    }
    
    close(listenFd);
    return 0;
}